<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\CommonApi;
use Illuminate\Support\Facades\DB;
use App\Model\User;
use Illuminate\Support\Facades\Redis;
use session;
use Lixunguan\Yuntongxun\Sdk as Yuntongxun;

class UserController extends Controller
{
    public function registerView()
    {
        return view('Home/register');
    }

    public function loginView()
    {
        return view('Home/login');
    }

    //加载个人中心页面
    public function userCenter(Request $request)
    {
       // $request->session()->has('username');
        // if ($request->session()->has( 'username' )) {
        //     // echo 11;
        //     $username = $request->session()->get( 'username' );
        //     $user = User::select(['id', 'user_name', 'name', 'password', 'phone', 'sex', 'email'])->where('user_name',  $username)->first(); 
        //     // dd($user->sex);
        //      return view('Home/usercenter', ['userdata' => $user]);

        // } else {
        //     // echo 22;exit;
           
        // }
        return view('Home/usercenter');
        
    }


    /**
     * 处理注册验证
     * @author chenxiaodong <229168653@qq.com>
     * @param $request  Request的对象
     * @return json    返回的数据是json数据  用户已经存在
     */
    public function doRegister(Request $request) 
    {
        // var_dump($_POST);
        $name = $request->input('name');
        $pass = $request->input('pass');
        $repass = $request->input('repass');
        $email = $request->input('email');
        $phone = $request->input('phone');
        $user = User::select(['id', 'user_name', 'password', 'phone'])->where('user_name', $name)->first();
        $phonecheck = User::select(['id', 'user_name', 'password', 'phone'])->where('phone', $phone)->first();

       if ($user) {
            echo json_encode(['status'=>1, 'msg'=>'用户名已被注册！']);
            // return false;
            exit;
       }
       if ($phonecheck) {
            echo json_encode(['status'=>2, 'msg'=>'该手机号码已被注册！']);
            exit;
       }      
       return true;
      
    }

     /**
     * 处理注册插入数据库
     * @author chenxiaodong <229168653@qq.com>
     * @param $request  Request的对象
     * @return json    返回的数据是json数据  成功返回true跳转登录页
     */
    public function addRegisterData(Request $request) 
    {

        //判断用户名是否合格
       if (!preg_match("/^[a-zA-Z][a-zA-Z0-9_-]{3,10}$/", $_POST['name'])) {
            // echo '账号不合法';
            echo json_encode('error');
            exit;
        }
        //判断密码是否合法
        $pass = preg_match('/^\S{6,20}$/', $_POST['pass']);
        if ($pass ==0) {
            // echo '密码不合法';
            echo json_encode('error');
            exit;
        }

        //两次密码判断是否一致
        if($_POST['pass']!==$_POST['repass']){
            // echo '两次密码不一致，请重新输入';
            echo json_encode('error');
            exit;
        }

         //  //判断邮箱是否合法
        if (!preg_match('/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/',$_POST['email'])) {
            // echo '邮箱不合法';
            echo json_encode('error');
            exit;
        }

        // //判断手机号码是否合法
        if (!preg_match('/^1[34578]\d{9}$/', $_POST['phone'])) {
            // echo '手机不合法';
            echo json_encode('error');
            exit;
        }

        $bool = $this->doRegister($request);
        // var_dump($bool);exit;
        //判断是否注册过
        if ($bool) {
            $phonecode = $this->phoneCode();
            if ($phonecode->statusCode==000000) {

                $password = password_hash($_POST['pass'], PASSWORD_DEFAULT);

                // var_dump($password);
                // exit;
                $data = [
                    'user_name'=>$_POST['name'],
                    'email'=>$_POST['email'],
                    'password'=>$password,
                    'status'=>0,
                    'phone'=>$_POST['phone'],
                    'add_time'=>time()
                ];

                $result = User::insert($data);
                if ($result) {
                     echo json_encode(['status'=>3, 'msg'=>'注册成功！']);
                     return;
                } else {
                     echo json_encode(['status'=>4, 'msg'=>'注册失败！']);
                     return;
                }

            } else {

                echo json_encode(['status'=>5, 'msg'=>'手机验证码不正确！']);
                return;
            }
            
        }
   
    }

    //手机验证码
    public function phoneCode() 
    {        
        // var_dump($arr);exit;
        $arr [] = rand(1000,9999);
        $sdk = new Yuntongxun('8a216da85ea31fdd015ebc557443078f', '8aaf07085e7ed569015e841fe314026e','fdfb45245dd44ff8858387074bfdb455');
        $sms = $sdk->sendTemplateSMS($_POST['phone'], $arr, 1);
        // print_r($sms->statusCode);
        return $sms;
        // print_r($sms);
        // var_dump($_POST['phone']);
    }


    /**
    * 前台登录处理
    * @author chenxiaodong <229168653@qq.com>
    * @param $request  Request的对象
    * @return json  返回的数据是json数据  成功返回true跳转首页，失败返回登录信息有误
    */
    public function doLogin(Request $request)
    {
        $name = $request->input('name');
        $pass = $request->input('pass');
        $user = User::select(['user_name', 'id', 'password'])->where('user_name', $name)->first();
        // dd($user->id);
        // $userkey = $user->id.$user->user_name;
        // $request->session()->put('username', $user->user_name);
        //  $value = $request->session()->get( 'username' );

        // dd($value);
        
        //使用redis判断密码错误次数
        $redis = new \Redis;
        $redis->connect('127.0.0.1', 6379);

        $num = $redis->get($name) ? $redis->get($name) : 0;

        if($num >= 3) {
           echo json_encode(['status'=>3, 'msg'=>'登录次数超过3次,请半小时后再登录']); //登录次数大于等于3次, 禁用半小时
            return;
        }   
        //判断验证码是否正确
        $CheckCode = CommonApi::CheckCode($request,'code');
        if (!$CheckCode) {
          echo json_encode(['status'=>100, 'msg'=>'验证码错误！']);
           return;
        }
        
         //判断用户是否存在
        if (!$user) {
            echo json_encode(['status'=>2, 'msg'=>'用户名不正确！']);
            return;
        }
        // 加密后密码判断
        // password_verify($pass, $user->password);
        // //判断密码是否正确
        if ( password_verify($pass, $user->password)) {

            if($num) {
                $redis->del($name);
            }

            //将用户名存放seesion中
            $request->session()->put('username', $user->user_name);
            $request->session()->put('userid', $user->id);

            echo json_encode(['status'=>1, 'msg'=>'正在登录中...']); 
            return;

        } else {
            $num++;
            $redis->set($name, $num, 1800);
            echo json_encode(['status'=>0, 'msg'=>'登录失败,账号或密码错误, 错误次数'. $num]);
            return;

        }
    
    }

  
    /**
    * 执行用户退出操作
    * @author chenxiaodong <229168653@qq.com>
    * @param $request  Request的对象
    * @return 返回true跳转登录页 删除session中键为username的值
    */
    public function loginOut(Request $request)
    {
        $request->session()->forget('username');
        $request->session()->forget('userid');
        return view('/Home/login');
    }

}
